#include <iostream>
using namespace std;
#include <sys/types.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
/*错误码*/
int g_exitStatus = 17;
int main()
{
#if 0
    pid_t pid = getpid();
    /*进程号*/
    cout<<"pid:"<<pid<<endl;
    /*父进程号*/
    pid_t ppid = getppid();
    cout<<"ppid:"<<ppid<<endl;
    /*进程组号*/
    int cnt = 10;
    while(cnt--)
    {
        sleep(1);
    }

    return 0;
#endif
    int val = 100;
    pid_t pid = fork();
    if(pid == -1)
    {
        /*说明创建子进程失败*/
        perror("fork error");
        exit(-1);
    }
    else if(pid == 0)
    {
       sleep(3);
        /*子进程*/
       cout<<"child process pid:"<<getpid()<<endl;
        cout<<"child process"<<endl;
        cout<<"child process paeent pid:"<<getppid()<<endl;
        /*退出进程*/
        _exit(g_exitStatus);

        /*如何拿到父进程的10100的value值*/
        cout<<"child process val= "<<val<<endl;
        int fd = open("./recoed.txt",O_RDONLY);
        read(fd,&val,sizeof(int));
        cout<<"child process val= "<<val<<endl;
        close(fd);
    }
    else
    {
        /*想让谁先执行，就让谁先fork
        fork默认先是父进程先执行，vflok让子进程先执行
        */
        sleep(1);
        /*回收子进程pid*/
        int childStatus = 0;
        /*下面两种方式是等价的，0阻塞，1非阻塞，2无限等待*/
        // wait(&childStatus);
        waitpid(pid,&childStatus,WNOHANG);
        cout<<"childStatus:"<<childStatus<<endl;
        cout<<"childStatus:"<<WIFEXITED(childStatus)<<endl;
        /*阻塞block*/

        /*父进程*/
        cout<<"parent process ret pid:"<<pid<<endl;
        cout<<"parent process"<<endl;
        cout<<"parent process ppid:"<<getpid()<<endl;
        cout<<"parent process val= "<<val<<endl;
        val += 10000;
        cout<<"parent process val= "<<val<<endl;
        /*父进程写数据*/
        const char *filename = "./recoed.txt";
        int fd = open(filename,O_RDWR|O_CREAT,0644);
        int writeBytes = write(fd,(const void*)&val,sizeof(int));
        close(fd);
    }
    cout<<"hello world"<<endl;
    int cnt = 100;
    while(cnt--)
    {
        sleep(1);
    }

}